'use strict'

import { app, protocol, BrowserWindow, ipcMain, dialog, clipboard } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require("path")
const { exec } = require('child_process');
const crypto = require('crypto');
const fs = require("fs")

// 软件版本（公测版、正式版、开发版）
const version = "开发版"

// 使用期限
const timeLimit = 1946610402

// 机器码
const macheineCode = 'c8c4d74803f73a7a473f8ee9e0f8105e'
const md5_str = 'chenxun'
const defaultMacheineCode = MD5_DEC(macheineCode + md5_str)

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // const targetDisplay = screen.getAllDisplays()[1];
  console.log(__dirname);
  // 获取应用程序路径
  const appPath = app.getAppPath();
  // Create the browser window.
  const win = new BrowserWindow({
    // 窗口尺寸
    // width: 1600 * 0.9,
    // height: 1200 * 0.9,
    width: 1650,
    height: 950,
    frame: false,
    // 生成位置
    // x: targetDisplay.bounds.x,
    // y: targetDisplay.bounds.y,
    // 渲染进程配置项
    webPreferences: {
      // preload: path.join("D:\\2K17Hook_code\\code\\src", 'preload.js'),
      preload: path.join(__dirname, 'preload.js'),
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })



  // IPC 监听最小化、最大化和关闭窗口事件
  ipcMain.on('minimization', () => {
    win.minimize();
  });
  // IPC 监听最大化
  ipcMain.on('minimize', () => {
    if (win.isMaximized()) {
      win.restore();
    } else {
      win.maximize();
    }
  });
  // IPC 监听关闭窗口事件
  ipcMain.on('cross', () => {
    win.close();
  });

  // 设置窗口名称
  win.setTitle('Waigua+');

  // 设置窗口的最小和最大宽度
  win.setMinimumSize(1024, 768);

  win.webContents.send('app-path', appPath);

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) {
      win.webContents.openDevTools()
    }
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
    // win.webContents.openDevTools()
  }
}


// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  // console.log(__dirname.indexOf("app.asar"));
  let dir = __dirname.indexOf("app.asar") != -1 ? pathResolve(__dirname) : __dirname
  console.log(dir);

  if (version === "开发版") {
    // 开发版本
    createWindow()
  }
  else if (version === "公测版") {
    // 公测版本
    if (Math.floor(Date.now() / 1000) > timeLimit) {
      myAlert("使用期限结束，请找群主更新")
    }
    else {
      // 创建视窗 
      createWindow()
    }
  }
  else if (version === "正式版") {
    // 正式版
    machineCodeVertify(() => {
      // 创建视窗
      createWindow()
    })
  }
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

// 一机一码验证
function machineCodeVertify(fun) {
  // 路径重置
  let dir = __dirname.indexOf("app.asar") != -1 ? pathResolve(__dirname) : __dirname
  // 执行exe
  exec(path.join(dir, 'store', 'verification.exe'), { encoding: 'utf8' }, (error) => {
    if (error) {
      console.log(error);
      // 写入日志
      fs.appendFileSync(
        path.join(dir, "log.txt"),
        `${new Date().toLocaleString()} - verification.exe运行失败:${error}\n`
      );
      myAlert('verification.exe运行失败:', () => {
        app.quit()
      })
    }
    // 读取剪切板内容
    const clipboardText = clipboard.readText();
    console.log('剪贴板内容:', clipboardText);
    // 测试加密验证码
    // let testCode = '08b29f3e8f4d25815121af4941f42cc9da0749804a54fa7bbededc5882489235419b08d1a355845c34ed39b181735f3a1a6306ff7b886c3d012f4bee7ca37790'
    // AES解密
    let decryptResult = AESdecrypt(clipboardText)
    console.log("AES解密:" + decryptResult)
    // 字符替换解密
    decryptResult = charSubDecrypt(decryptResult)
    console.log("字符替换解密:" + decryptResult)
    // 字符串切割解密
    decryptResult = stringCuttingDecrypt(decryptResult)
    console.log("字符串切割解密:" + decryptResult)
    // 时间戳验证
    let timeResult = timeStampDecrypt(decryptResult.substring(0, 16))
    let timeFlag = timeResult.flag
    let timeDistance = timeResult.distance
    console.log("时间戳验证:" + timeFlag)
    // 机器码验证
    let macheineCodeFlag = decryptResult.substring(16) === defaultMacheineCode
    console.log("机器码验证:" + macheineCodeFlag)
    // 验证结果公布
    !timeFlag && myAlert("时间验证有误！验证间隔了" + timeDistance + "秒", () => {
      fs.appendFileSync(
        path.join(dir, "log.txt"),
        `${new Date().toLocaleString()} - 时间验证有误！\n验证间隔了${timeDistance}秒\n`
      );
    })
    !macheineCodeFlag && myAlert("机器码验证有误！", () => {
      fs.appendFileSync(
        path.join(dir, "log.txt"),
        `${new Date().toLocaleString()} -机器码验证有误！\n
        当前机器码为：${decryptResult.substring(16)}\n
        验证机器码为：${defaultMacheineCode}\n`
      );
    })
    macheineCodeFlag && timeFlag && myAlert("一机一码验证通过！", () => {
      fs.appendFileSync(
        path.join(dir, "log.txt"),
        `一机一码验证通过！\n
        当前机器码为：${decryptResult.substring(16)}\n
        验证时间间隔${timeDistance}秒\n`
      );
      fun()
    })
  });
}

// md5解密
function MD5_DEC(plaintext) {
  const str = plaintext;
  return crypto.createHash('md5').update(str).digest('hex')
}

// 解密AES
function AESdecrypt(encryptedText) {
  try {
    // aes密钥
    let key = '65023EC4BA7420BB';
    let decipher = crypto.createDecipheriv('aes-128-ecb', key, Buffer.from(''));
    let decrypted = decipher.update(hexToBase64(encryptedText), 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
  } catch (error) {
    console.error('AES decryption error:', error);
    return null;
  }
}


// 将hex编码的文本转换成 base64 
function hexToBase64(hexString) {
  try {
    let binary = Buffer.from(hexString, 'hex').toString('binary');
    return Buffer.from(binary, 'binary').toString('base64');
  } catch (error) {
    console.error('hexToBase64 error:', error);
    return null;
  }
}

// 字符替换解密
function charSubDecrypt(inputString) {
  // 替换规则映射
  const replacements = {
    '.': '=',
    '/': '5',
    '+': '8'
  };

  // 使用正则表达式替换所有匹配项
  let modifiedString = inputString.replace(/[.\/+]/g, match => replacements[match]);

  return modifiedString;
}

// 字符串切割解密
function stringCuttingDecrypt(inputString) {
  let string1 = "";
  let string2 = "";
  for (let index = 0; index < inputString.length; index += 4) {
    string1 += inputString[index] + inputString[index + 1]
    string2 += inputString[index + 2] + inputString[index + 3]
  }
  return string1 + string2;
}

// 时间戳解密
function timeStampDecrypt(inputString) {
  // 传入的时间戳
  let pyTimeStamp = Buffer.from(inputString, 'base64').toString('binary')
  // console.log(pyTimeStamp,Math.floor(Date.now() / 1000))
  // 当前的时间戳
  let jsTimeStamp = Math.floor(Date.now() / 1000);
  console.log("时间戳比较：" + timestampToDateTime(pyTimeStamp), timestampToDateTime(jsTimeStamp))
  // 判断是否间隔过久
  let diff = 10
  return {
    flag: Math.abs((pyTimeStamp - jsTimeStamp) / 1000) < diff,
    distance: Math.abs((pyTimeStamp - jsTimeStamp) / 1000)
  }
}

// 时间戳转现实时间
function timestampToDateTime(timestamp) {
  let milliseconds = timestamp * 1000;
  let dateObject = new Date(milliseconds);
  return dateObject.toLocaleString(); // 返回本地时间的字符串表示
}

// 提示框
function myAlert(text, fun) {
  dialog.showMessageBox({
    type: 'info',
    title: '提示',
    message: text,
    buttons: ['确定']
  }).then(result => {
    fun()
  }).catch(err => {
    console.log(err);
  });
}

// 路径去尾
function pathResolve(testPath) {
  // let testPath = "C:\\Users\\liang\\AppData\\Local\\Programs\\WaiguaPlus2.0\\resources\\app.asar"
  let arrList = testPath.split("\\")
  arrList.pop()
  let newStr = arrList.map((word, index) => {
    if (index === 0) {
      return word; // 第一个单词不添加逗号
    } else {
      return '\\' + word; // 其他单词前添加逗号
    }
  }).join('');
  return newStr
}